<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属科室" prop="deptName" class="item">
        <treeselect v-model="queryParams.deptId" clearable :options="deptOptions" 
        @keyup.enter.native="handleQuery" style="width:200px;"
        :disable-branch-nodes="false" :show-count="true" placeholder="请选择所属科室" />
      </el-form-item>
      <el-form-item label="人员姓名" prop="userName" class="item">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入人员姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="评级" prop="rating" class="item">
        <el-select v-model="queryParams.rating" placeholder="请选择评级" clearable size="small">
          <el-option
            v-for="dict in ratingOptions"
            :key="dict.dictLabel"
            :label="dict.dictLabel"
            :value="dict.dictLabel"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ability:details:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ability:details:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ability:details:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ability:details:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属科室" align="center" prop="deptName" />
      <el-table-column label="人员姓名" align="center" prop="user.nickName" />
      <!-- <el-table-column label="所属组别" align="center" prop="user.groupType" :formatter="isSubmitGroupTypeFormat"/> -->
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="评级" align="center" prop="rating"/>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ability:details:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ability:details:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false" >

      <el-form ref="form" :rules="testRules" :model="form" label-width="80px"  v-loading="loading">
        <el-input v-model.number="form.deptId" placeholder="机构ID" v-if="false"/>
        <el-input v-model.number="form.recordId" placeholder="考试ID" v-if="false"/>
        <el-form-item prop="userId" label="人员姓名">
          <!-- <treeselect v-model="form.userName" :options="peopleOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择人员姓名" :normalizer="normalizer" /> -->
          <el-select v-model="form.userId" clearable  style="width:380px">
            <el-option v-for="item in usersOptions" :key="item.userId" :label="item.nickName" :value="item.userId" :disabled="item.states == 1" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model.number="form.score" placeholder="请输入分数" /><!--  @keyup.enter.native="submitForm" -->
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="loading" >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDetails, getDetails, delDetails, addDetails, updateDetails, exportDetails, UsersList,getUsers} from "@/api/ability/people/details";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Details",
  components: { Treeselect },
  data() {
      // 成绩的表单验证
      var scoreRules = (rule, value, callback) => {
        if (!Number.isInteger(value)) {
          return callback(new Error('成绩不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value < 0) {
              callback(new Error('成绩必须是正数'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试详情表格数据
      detailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //组别
      groupTypeOptions: [],
      // 评级字典
      ratingOptions: [],
      // 部门树选项
      deptOptions: [],
      // 人员选项
      usersOptions: [],
      // 部门人员选项
      peopleOptions:[{
        id:"",
        label:"",
        type:"",
        depts: [{
            id: "",
            label:"",
            type:"",
        }],
      }],
     normalizer(node) {
        if(node.userId!=undefined){
            return {
            id: node.userId,
            label: node.userName,
            children: node.depts
            }
        }else{
            if(node.users&&node.users.length!=0){
                node.depts=node.users
                // console.log(node.userName,"aaa")
            }return {
                id: node.id,
                label: node.label,
                children: node.depts
                }
            }
        },

      // 查询参数
      queryParams: {
        recordId: null,
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        userName: null,
        rating: null,
      },
      // 表单参数
      form: {
        userId:'',
        score:'',
        remark:''
      },
      // 表单校验
      testRules: {
          userId: [
            { required: true, message: '请选择人员姓名', trigger: 'blur' }
          ],
          score:[
            { required: true, validator: scoreRules, trigger: 'blur' }
          ]
      },

    };
  },
  mounted(){
    if(this.$route.query.id){
      this.queryParams.recordId = this.$route.query.id;
      this.queryParams.deptId =  this.$route.query.data.deptId;
      console.log("deptId"+this.queryParams.deptId);
      this.getList();
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getUsersList(this.queryParams.deptId);
    this.getDicts("ability_exam_rating").then(response => {
      this.ratingOptions = response.data;
    });
    this.getDicts("sys_group_list").then((response) => {
      this.groupTypeOptions = response.data;
    });
  },
  methods: {
    beforeunloadHandler(e) {
      e = e || window.event;
        if(e){window.close();}
    },
    // 所属组别字典翻译
    isSubmitGroupTypeFormat(row, column) {
      return this.selectDictLabel(this.groupTypeOptions, row.user.groupType);
    },
    /** 查询考试详情列表 */
    getList() {
      this.loading = true;
      listDetails(this.queryParams).then(response => {
        this.detailsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询用户下拉树结构 */
    getUsersList(deptId) {
      UsersList(deptId).then((response) => {
        this.peopleOptions = response.data;
      });
    },
    /** 查询未录入用户下拉 */
    getNoUsersList(recordId,deptId) {
      getUsers(recordId,deptId).then((response) => {
        this.usersOptions = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 评级字典翻译
    ratingFormat(row, column) {
      return this.selectDictLabel(this.ratingOptions, row.rating);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        detailsId: null,
        dept: null,
        userId: null,
        userName: null,
        score: null,
        rating: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
      this.getNoUsersList(this.queryParams.recordId,null);
      this.form.recordId = this.queryParams.recordId;
      this.form.deptId = this.queryParams.deptId;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.detailsList=this.detailsList.filter((item)=>{
        return item.userName==this.queryParams.userName||item.dept==this.queryParams.dept
      })
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.detailsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getUsersList();
      this.form.deptId =  this.queryParams.deptId;
      this.form.recordId = this.queryParams.recordId;
      this.getNoUsersList(this.queryParams.recordId,null);
      this.open = true;
      this.title = "添加考试详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getUsersList();
      this.getNoUsersList(this.queryParams.recordId,this.queryParams.deptId);
      const detailsId = row.detailsId || this.ids
      getDetails(detailsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考试详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      var isclick = false;
      this.$refs["form"].validate(valid => {
        if (valid&&!isclick) {
          isclick = true;
          if (this.form.detailsId != null) {
            updateDetails(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                isclick = false;
              }
            });
          } else {
            addDetails(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = true;
                this.getList();
                this.reset();
                isclick = false;
              }
            });
          }
          
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const detailsIds = row.detailsId || this.ids;
      this.$confirm('是否确认删除考试详情编号为"' + detailsIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDetails(detailsIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    }, 
    /** 获取部门用户下拉框 */
    handleDeptUser(row) {
      getDeptUser(100).then((response) => {
        this.deptOptions = response.data;
      });
    },


    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有考试详情数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportDetails(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
